<?php
/**
 * Created by PhpStorm.
 * User: 69568
 * Date: 2018/2/8
 * Time: 13:29
 */

namespace App\Http\Controllers\Api;


use App\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Resources\GiftResource;
use App\Http\Resources\MoneyLogRescource;
use App\Models\Gift;
use App\Models\MoneyLog;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class GiftController extends Controller
{
    use ApiResponse;

    public function index(Request $request)
    {
        $user_id = $request->user('api')->id;
        $gifts = Gift::query()->where('user_id', $user_id)->paginate();
        return $this->message('获取成功', GiftResource::collection($gifts));
    }

    public function detail(Request $request)
    {
        $user_id = $request->user('api')->id;
        $id = $request->input('id', 0);
        if ($id) {
            $gift = Gift::whereId($id)->where('user_id', $user_id)->first();
            $logs = MoneyLog::whereOrderNo($gift->order_no)->where('user_id', $user_id)->where('type', 'gift')->get();
            return $this->message('获取成功', MoneyLogRescource::collection($logs));
        } else {
            return $this->message('获取失败', [], 400);
        }
    }

    public function receive(Request $request)
    {
        $user_id = $request->user('api')->id;
        $id = $request->input('id', 0);
        if ($id) {
            $gift = Gift::whereId($id)->where('user_id', $user_id)->first();
            $now = Carbon::now();
            $logs = MoneyLog::whereOrderNo($gift->order_no)->where('user_id', $user_id)->where('type', 'gift')->where('pay_status', false)->whereDate('pay_at', '<=', $now)->get();
//            dd($logs);
            if (empty($logs) || $logs->count() == 0) {
                return $this->message('暂无可领取的津贴', [], 400);
            } else {

                /** @var \App\Models\User $user */
                $user = $request->user('api');
                /** @var \App\Models\MoneyLog $log */
                foreach ($logs as $log) {
                    $user->money += $log->money;
                    $log->pay_status = true;
                    $gift->send++;
                    $gift->save();
                    $log->save();
                }
                $user->save();
                return $this->message('领取成功');
            }
        }
    }
}